#' Check your bib file to make sure that each item has been evaluated for inclusion
#' @author Joseph Henry \email{joseph.henry@@sydney.edu.au}
#' @date 6 July 2012  

EvaluatedCheck <- function (bib.file, in.out.tags){
#' @param bib.file (character)  full path and name of input .bib file  (including extension) 
#' @param	number.of.kappa.files (character) tag for all studies used in kappa analysis
#' ALL TAG CODES MUST BE: as.character (numeric)
#' @param in.out.tags (character) tags for inclusion and exclusion
#' @output (matrix) each bib item and its evaluation status

#' Packages
require (operators)

#' Small function
Title_key_extract <- function (o1,choice){
	o2_start <- grep("@",substring (o1,1,1))
	o2_finish <- c(grep("\\},",substring (o1,1,2)),length(o1)) # add last one)
	o2_ref_groups <- cbind (STA = o2_start, FIN = o2_finish)
	o2_key_list <- list()
	o2_title_list <- list()
	for (i in 1:nrow (o2_ref_groups)){
		f1 <- o1[o2_ref_groups[i,1]:o2_ref_groups[i,2]]
		f2 <- substring (f1,2,6)
		o2_key_list[[i]] <- f1[grep("keywo",f2,value= FALSE)]
		if(choice != "ID"){
			o2_title_list[[i]] <-	f1[grep(choice,f2,value= FALSE)]
		} else {
			o2_title_list[[i]] <-	f1[1]
		}
	}
	# Combine
	o2_key_list_NA <- sapply(o2_key_list, function (x) ifelse(length(x)==0,NA,x))
	o2_title_list_NA <- sapply(o2_title_list, function (x) ifelse(length(x)==0,NA,x))
	o2_combined <-cbind(KEY=o2_key_list_NA,TIT=o2_title_list_NA)
	return (o2_combined)
}

# Load
  Data_Read <- readLines (bib.file)
	
# Clean
  # Extract keywords and ID	
	  ID_KW_raw <- Title_key_extract(Data_Read,"ID")
		ID_KW_clean <- ID_KW_raw
		ID_KW_clean[,1] <- gsub(",","",str_replace (ID_KW_clean[,1],"(.*\\{)(.*)(\\})","\\2"))
		ID_KW_clean[,2] <- str_replace (ID_KW_clean[,2],"(.*\\{)(.*)(,)","\\2")
	Tags_Sep <- strsplit(ID_KW_clean[,1]," ") # Separate the tags
	Tags_Count <- sapply (Tags_Sep, length) # Count the tags for each id
	# Repeat the id name
		Rep_list <- list()
		for(i in 1:length (Tags_Count)){
			Rep_list[[i]] <- rep (ID_KW_clean[i,2],Tags_Count[i])
		}
		ID_KW_df_raw <- data.frame(ID=unlist (Rep_list),TAG = unlist (Tags_Sep))
	ID_KW_df<-ID_KW_df_raw[-(grep("[a-zA-Z]",as.character(ID_KW_df_raw$TAG))),] 	# Extract only numbered tags

# Do	
	Checklist <- lapply(split(ID_KW_df,ID_KW_df$ID),function (x){
		xTAG <- as.character(x$TAG)
		out <- ifelse(length(unique(xTAG %!in% in.out.tags))==1,"not done","done")
		return (out)
	})
	
	Checkmat <- data.frame(PAPER = names (CheckList),JUDGED = unlist(CheckList))

# Return	
	return (Checkmat)
}

